<template>
  <el-dialog
    v-model="d.isVisble"
    title="选择模板"
    width="980px"
    custom-class="templateDialog-container"
    @closed="closed"
  >
    <div class="template-header">
      <el-form>
        <el-row v-if="showType !== 3">
          <el-col :span="24">
            <el-form-item label="治疗方案类别:" label-width="120px">
              <el-radio-group
                v-model="d.form.treatmentPlanType"
                @change="treatmentPlanChange"
              >
                <el-radio
                  v-for="(item, index) in treatmentPlans(actionPlanValue)"
                  :key="'treatmentPlanTypes_' + index"
                  :value="item.value"
                  :label="item.label"
                ></el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col
            v-if="
              (showType === 1 || showType === 2) &&
              form.treatmentPlanType !== '缓解药物治疗方案'
            "
            :span="8"
          >
            <el-form-item
              :label="isAcuteTitle(d.form.treatmentPlanType)"
              label-width="120px"
            >
              <el-select
                v-model="d.form.controlLevel"
                @change="loadData"
                clearable
              >
                <el-option
                  v-for="(item, index) in controlLevelsWithDefalut"
                  :key="'controlLevels_' + index"
                  :value="item.value"
                  :label="item.label"
                >
                  <span style="float: left">{{ item.label }}</span>
                  <span style="color: red; font-size: 13px">
                    {{ item.subTitle }}
                  </span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="模板内容筛选：" label-width="120px">
              <el-input
                v-model="d.form.medicineName"
                @input="loadData"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <!-- <h3>模板</h3> -->
    <div class="template-body">
      <div
        class="treatment-items"
        v-if="
          d.form.treatmentPlanType === '当前急性发作治疗方案' || showType === 3
        "
      >
        <h3>{{ leftTitle }}</h3>
        <div
          v-for="item in projects"
          @click="setChecked('project', item)"
          class="treatment-item-item"
          :class="{
            checked: projectChecks.includes(item.parentID),
            active: item.parentID === d.actionID,
          }"
          :key="'treatment_items_' + item.parentID"
        >
          <div
            class="treatment-item-checker"
            @click.stop="cancelChecked('project', item)"
          >
            <i class="el-icon-close" style="font-size: 22px"></i>
          </div>
          {{ item.parentID }}
        </div>
        <div v-if="!projects.length" class="none-data">数据为空</div>
      </div>
      <div
        class="treatment-tpls"
        :style="{
          'margin-left':
            d.form.treatmentPlanType !== '当前急性发作治疗方案' ||
            showType !== 3
              ? '0'
              : '250px',
        }"
      >
        <h3>模板</h3>
        <div
          v-for="item in d.items"
          class="treatment-tpl-item"
          @click.stop="setChecked('item', item)"
          :class="{ checked: itemChecks.includes(item.id) }"
          :key="'treatment_tpls_' + item.id"
        >
          <el-tag
            v-if="item.recommend"
            type="warning"
            size="small"
            style="position: absolute; top: 8px; right: 55px"
          >
            推荐
          </el-tag>
          <el-tag
            type="success"
            size="small"
            style="position: absolute; top: 8px; right: 8px"
          >
            {{ item.type }}
          </el-tag>
          <div class="tpl-content">
            <div>{{ item.title }}</div>
          </div>
          <div class="tpl-desc">{{ item.remark }}</div>
        </div>
        <div v-if="!d.items.length" class="none-data">数据为空</div>
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="d.isVisble = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script>
  import { computed, reactive, toRefs, unref } from 'vue'
  import emr from '@/hooks/emr.vue'
  import {
    loadNormalTempLate,
    loadAcuteTemplate,
  } from '@/api/modules/actionPlan'
  import { useStore } from 'vuex'
  import common from '@/utils/common'
  export default {
    name: 'templateDialog',
    props: {
      emrId: String,
      // 控制水平评估
      recommendControLevel: String,
      // 急性严重程度推荐
      recommendAcuteSeverity: String,
      leftTitle: {
        type: String,
        default() {
          return '项目'
        },
      },
    },
    emits: ['selResult'],
    setup(props, context) {
      const d = reactive({
        type: 1,
        treatmentItems: [],
        form: {
          treatmentPlanType: null,
          controlLevel: null,
          medicineName: null,
        },
        isVisble: false,
        projects: [],
        actionID: null,
        projectChecks: [],
        items: [],
        itemChecks: [],
        actionPlanValue: null,
        showType: null,
      })
      const store = useStore()

      const loadNormalTempLateList = async function (params) {
        const res = await loadNormalTempLate(params)
        d.items = res.data
      }

      const loadAcuteTemplateLList = async function (params) {
        const res = await loadAcuteTemplate(params)
        Object.keys(res.data).forEach((key) => {
          d.projects.push({
            items: res.data[key].map((item) => {
              item.parentID = key
              return item
            }),
            parentID: key,
          })
        })

        console.log('d.projects =' + JSON.stringify(d.projects))
        for (let i = 0; i < d.projects.length; i++) {
          const { items } = d.projects[i]
          for (let j = 0; j < items.length; j++) {
            const { recommend, parentID } = items[j]
            if (recommend) {
              d.items = items
              d.actionID = parentID
              break
            }
          }
          if (d.actionID) break
        }
      }

      const treatmentPlanChange = function () {
        d.form.controlLevel = null
        autoDefaultSelect(d.form.treatmentPlanType)
        // d.form.treatmentPlanType
        loadData()
      }
      const loadData = function () {
        const searchData = {
          templateType: d.templateType,
          actionPlanType: d.actionPlanValue,
          ageName: store.getters.patientInfo.ageName,
          weight: store.getters.patientInfo.weight,
          controlLevel: d.form.controlLevel,
          treatmentPlanType: d.form.treatmentPlanType,
          medicineName: d.form.medicineName,
          medicalRecordId: props.emrId,
        }
        clearList()
        if (
          d.form.treatmentPlanType === '当前急性发作治疗方案' ||
          d.showType === 3
        ) {
          if (d.showType === 3) searchData.treatmentPlanType = null
          loadAcuteTemplateLList(searchData)
        } else {
          loadNormalTempLateList(searchData)
        }
      }
      function autoDefaultSelect(treatmentPlanType) {
        const { recommendControLevel, recommendAcuteSeverity } = props
        // 有控制水平首先显示控制水平，只有急性显示急性
        if (recommendControLevel && !treatmentPlanType) {
          d.form.treatmentPlanType = '控制药物治疗方案'
          d.form.controlLevel = recommendControLevel
        } else if (recommendAcuteSeverity && !treatmentPlanType) {
          d.form.treatmentPlanType = '当前急性发作治疗方案'
          d.form.controlLevel = recommendAcuteSeverity
        } else if (
          treatmentPlanType === '当前急性发作治疗方案' &&
          recommendAcuteSeverity
        ) {
          d.form.controlLevel = recommendAcuteSeverity
        } else if (
          (treatmentPlanType === '控制药物治疗方案' ||
            treatmentPlanType === '整体治疗方案') &&
          recommendControLevel
        ) {
          d.form.controlLevel = recommendControLevel
        }
      }
      const initData = function (actionPlanValue, showType, templateType) {
        /**
         *  弹窗样式 showType
         * 1. 标准版 治疗方案类别 + 控制级别 + 模板内容筛选 + 单列/双列
         * 2. 简易版 控制级别 + 模板内容筛选 + 单列
         * 3. 模板内容筛选 + 双列
         */
        d.isVisble = true
        d.actionPlanValue = actionPlanValue
        d.showType = showType
        d.templateType = templateType
        autoDefaultSelect()
        loadData()
      }
      const setChecked = function (type, item) {
        if (type === 'item') {
          const isCheck = d.itemChecks.includes(item.id)
          if (isCheck) {
            d.itemChecks.splice(d.itemChecks.indexOf(item.id), 1)
            d.projectChecks.splice(d.projectChecks.indexOf(item.parentID), 1)
          } else {
            d.itemChecks.push(item.id)
            d.projectChecks.push(item.parentID)
          }
        } else if (type === 'project') {
          d.items = item.items
          d.actionID = item.parentID
        }
      }
      const cancelChecked = function (type, item) {
        const ids = item.items.map((cell) => cell.id)
        ids.forEach((id) => {
          d.itemChecks.splice(d.itemChecks.indexOf(id), 1)
        })

        function del(parentID) {
          d.projectChecks.splice(d.projectChecks.indexOf(parentID), 1)
          if (d.projectChecks.includes(parentID)) del()
        }
        del(item.parentID)
      }

      const getCheckData = function () {
        let all = d.items
        if (
          d.form.treatmentPlanType === '当前急性发作治疗方案' ||
          d.showType === 3
        )
          all = d.projects.reduce((prev, curr) => {
            if (!prev) return curr.items
            return prev.concat(curr.items)
          }, false)
        return all.filter((item) => d.itemChecks.includes(item.id))
      }
      const onSubmit = function () {
        const checkData = getCheckData()
        if (checkData.length === 0) {
          common.XmMessage(3, '至少添加一项')
          return
        }
        const tmp = [
          'actionYellow',
          'usageYellow',
          'usageRed',
          'actionRed',
          'usageGreen',
          'emergencyUse',
          'actionGreen',
        ]
        const items = checkData.reduce((prev, curr) => {
          if (!prev) return curr.content
          tmp.map((item) => {
            if (!prev[item]) prev[item] = []
            if (curr.content[item])
              prev[item] = prev[item].concat(curr.content[item])
          })
          return prev
        }, false)
        d.isVisble = false
        context.emit('selResult', {
          selData: items,
          templateType: d.templateType,
        })
      }

      const closed = function () {
        console.log('closed')
        clearList()
        d.actionID = null
        d.actionPlanValue = null
        d.showType = null
        d.templateType = null
        d.form = {
          treatmentPlanType: null,
          controlLevel: null,
          medicineName: null,
        }
      }
      const clearList = function () {
        d.treatmentItems = []
        d.projects = []
        d.projectChecks = []
        d.items = []
        d.itemChecks = []
      }
      const { treatmentPlans, fitterControlLevelsFunc } = emr()
      const controlLevelsWithDefalut = computed(() => {
        return fitterControlLevelsFunc(d.form.treatmentPlanType).map((item) => {
          if (
            item.label === props.recommendControLevel &&
            d.form.treatmentPlanType !== '当前急性发作治疗方案'
          ) {
            return { label: item.label, subTitle: '(推荐)', value: item.value }
          }
          if (
            item.label === props.recommendAcuteSeverity &&
            d.form.treatmentPlanType === '当前急性发作治疗方案'
          ) {
            return { label: item.label, subTitle: '(推荐)', value: item.value }
          }
          return item
        })
      })
      return {
        treatmentPlans,
        controlLevelsWithDefalut,
        d,
        ...toRefs(d),
        initData,
        loadData,
        setChecked,
        cancelChecked,
        onSubmit,
        closed,
        treatmentPlanChange,
        ...toRefs(emr()),
      }
    },
  }
</script>
<style lang="scss">
  .templateDialog-container {
    &.el-dialog {
      margin-top: 5vh !important;
    }

    &.el-dialog .el-row {
      height: 44px;
    }

    .template-header {
      white-space: nowrap;
      padding: 6px 0px 12px;
      font-size: 16px;
      background-color: #eee;

      .template-cell {
        display: flex;
        align-items: center;
        margin-right: 10px;

        .el-select {
          background-color: #eee;
        }
      }
    }

    .template-body {
      margin-top: 12px;
      height: calc(100vh - 420px);
      overflow: hidden;

      .treatment-items {
        float: left;
        width: 250px;
        left: 0;
        top: 0;
        height: 100%;
        padding: 6px 12px;
        box-sizing: border-box;
        overflow: auto;
        border: 1px dashed #eee;
        border-radius: 2px;

        .treatment-item-item {
          padding: 8px;
          line-height: 2;
          border-radius: 2px;
          position: relative;
          // padding-left: calc(4rem + 4px);
          text-align: center;
          background-color: #fff;
          border: 1px dashed #f2f2f2;
          margin: 6px 0;
          font-size: 14px;
          display: -webkit-box;
          overflow: hidden;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 2;
          text-overflow: ellipsis;
          max-height: 3.4rem;
          color: #666;

          &.checked {
            border: 1px dashed #c8dbf7;
            color: #0066ad;

            .treatment-item-checker {
              position: absolute;
              top: 0;
              right: 0;
              height: 0px;
            }
          }

          &.active {
            border: 1px solid #c8dbf7;
            color: #0066ad;
            font-weight: bold;
          }

          .treatment-item-checker {
            position: absolute;
            top: 0;
            right: 0;
            height: 0px;
            // top: 0;
            // left: 0;
            // display: flex;
            // align-items: center;
            // justify-content: center;
            // height: 100%;
            // width: 4rem;
            // color: primary;
            // background-color: #c8dbf7;
            // font-size: 12px;
            // border: 1px dashed #c8dbf7;
            // cursor: pointer;
          }
        }
      }

      h3 {
        margin: 4px 8px;
      }

      .treatment-tpls {
        margin-left: 250px;
        padding: 6px 12px;
        height: 100%;
        overflow: auto;

        .treatment-tpl-item {
          padding: 12px;
          border-radius: 4px;
          background-color: #eee;
          margin: 0 0 0.5rem 0;
          color: #333;
          position: relative;

          &.checked {
            background-color: #c8dbf7;
            color: #fff;

            .tpl-desc,
            .tpl-content {
              color: #0066ad;
            }
          }
        }

        .tpl-desc {
          color: #999;
          font-size: 14px;
          margin-top: 1rem;
        }
      }

      // .cell-item {
      //   padding: 12px;
      //   border-radius: 4px;
      //   background-color: #eee;
      //   margin: 0 0 0.5rem;
      //   color: #333;
      //   &.checked {
      //     background-color: #c8dbf7;
      //     color: #0066ad;
      //   }
      // }
    }
  }
</style>
